
export const CreateStorage = (storage: Storage = localStorage) => {
  class WebStorage {
    public storage: Storage
    constructor() {
      this.storage = storage
    }

    set( key: string, value: any, expire: number | null | undefined = null ) {
      const stringiFyData = JSON.stringify({
        value,
        time: Date.now(),
        expire: expire ? new Date().getTime() + expire * 1000 : null
      })

      this.storage.setItem( key, stringiFyData )
    }


    get( key: string ): any {
      const val = this.storage.getItem( key )
      if( val === 'undefined' || val === null ) return null

      const data = JSON.parse( val )
      const { value, expire } = data

      if( !expire || expire >= new Date().getTime() ) {
        return value
      }

      // 如果缓存过期，则清除此缓存
      this.remove( key )
      return null
    }


    remove(key: string): void {
      this.storage.removeItem( key )
    }


    clear(): void {
      this.storage.clear()
    }

  }

  return new WebStorage()
}



